package com.xiaotu.model;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class MyFile implements MultipartFile {

    private File file;

    public MyFile(File file) {
        super();
        this.file = file;
    }

    public MyFile() {
        super();
    }

    @Override
    public String getName() {
        return null;
    }

    @Override
    public String getOriginalFilename() {
        return this.file.getName();
    }

    @Override
    public String getContentType() {
        return null;
    }

    @Override
    public boolean isEmpty() {
        return false;
    }

    @Override
    public long getSize() {
        return this.file.length();
    }

    @Override
    public byte[] getBytes() throws IOException {
        return File2byte(this.file);
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return null;
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {

    }

    /**
     * 将文件转换成byte数组
     *
     * @param tradeFile
     * @return
     */
    public byte[] File2byte(File tradeFile) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(tradeFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

}
